import time
import json
import uuid
from typing import List
from pydantic import BaseModel
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
import ssl
import random


class Parameter(BaseModel):
    bdf_path: str
    op2_path: str
    worker_num: int


class Result(BaseModel):
    eigenvalues: List[float]
    eigenvectors: List[float]


def get_request_id():
    return str(uuid.uuid1())


def generate_random(length=6):
    digits = random.sample('0123456789', length)
    random_number = int(''.join(digits))
    return random_number


def create_cluster(worker_num=2):
    # 禁用 SSL 证书验证（与 requests 的 verify=False 等效）
    ssl_context = ssl._create_unverified_context()

    url = "http://10.210.153.106:12021/cluster/createRayCluster"
    request_id = get_request_id()
    print('Create ray cluster request id: %s' % request_id)

    data = {
        "RequestId": request_id,
        "ClusterName": f"raycluster-{generate_random(6)}",
        "KubeConfPath": "/root/.kube/config",
        "Namespace": "ray-engine",
        "HeadNode": {
            "Image": "10.210.153.201:30001/fusion-engine/ray:v2.31.0-py311-cpu",
            "Cpu": 2,
            "Memory": "4G",
            "NodeAffinity": [],
            "EnvironmentVars": [
                {
                    "Name": "TEST_ENV",
                    "Value": "testing value",
                },
                {
                    "Name": "PIP_INDEX_URL",
                    "Value": "https://pypi.tuna.tsinghua.edu.cn/simple",
                }
            ],
        },
        "WorkerNodeGroups": [
            {
                "GroupName": "workergroup",
                "Image": "10.210.153.201:30001/fusion-engine/ray:v2.31.0-py311-cpu",
                "Cpu": 2,
                "Memory": "4G",
                "Replicas": worker_num,
                "NodeAffinity": [],
                "EnvironmentVars": [
                    {
                        "Name": "TEST_ENV2",
                        "Value": "testing value2",
                    },
                    {
                        "Name": "PIP_INDEX_URL",
                        "Value": "https://pypi.tuna.tsinghua.edu.cn/simple",
                    }
                ],
            },
        ]
    }

    try:
        # 将数据编码为 JSON 字节
        encoded_data = json.dumps(data).encode('utf-8')

        # 创建请求对象
        req = Request(url, data=encoded_data, method='POST')
        req.add_header('Content-Type', 'application/json')

        # 发送请求
        with urlopen(req, context=ssl_context) as response:
            response_data = response.read().decode('utf-8')
            received_data = json.loads(response_data)

            if response.status == 200 and received_data['result'] == 'Succeed':
                print("Received data:", received_data)
                return received_data['message']['data']['ClusterId']
            else:
                print("Request returned with status code:", response.status)
                print("Response:", received_data)

    except HTTPError as e:
        print(f"HTTP Error occurred: {e.code} - {e.reason}")
        if e.code == 400:
            error_body = e.read().decode('utf-8')
            print("Error details:", error_body)

    except URLError as e:
        print(f"URL Error occurred: {e.reason}")

    except json.JSONDecodeError as e:
        print(f"Failed to decode JSON response: {e}")

    except Exception as e:
        print(f"An unexpected error occurred: {e}")


def random_num(num=200):
    return [random.random() for _ in range(num)]


def main(param: Parameter) -> Result:
    create_cluster(param.worker_num)
    time.sleep(20)
    return Result(eigenvalues=random_num(), eigenvectors=random_num())